package com.prj.ufdm.cloud.svr.gateway.api;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;

import com.alibaba.fastjson.JSONObject;
import com.prj.ufdm.cloud.base.dto.RetData;
import com.prj.ufdm.cloud.base.dto.RetDataHead;
import com.prj.ufdm.cloud.base.util.BaseDateUtil;
import com.prj.ufdm.cloud.base.util.BaseUuidUtil;
import com.prj.ufdm.cloud.svr.gateway.bpo.LogBPO;
import com.prj.ufdm.cloud.svr.gateway.bpo.SysUserBPO;
import com.prj.ufdm.cloud.svr.gateway.bpo.SysUserRedisBPO;
import com.prj.ufdm.cloud.svr.gateway.config.RedisService;
import com.prj.ufdm.cloud.svr.gateway.constant.WebSecurityConstants;
import com.prj.ufdm.cloud.svr.gateway.enums.GatewayRetCodeEnum;
import com.prj.ufdm.cloud.svr.gateway.model.SysUser;

import reactor.core.publisher.Mono;

/**
 * 用户登录
 * @author 胡义振  
 * @date 2018年3月26日
 */
@RequestMapping(value = "/web/sysuser")
@RestController
public class SysUserLoginApi {
	
	@Autowired
	SysUserBPO sysUserBPO;
	
	@Autowired
	RedisService redisService;
	
	@Autowired
	SysUserRedisBPO sysUserRedisBPO;
	
	@Autowired
	LogBPO logBPO;

	@RequestMapping(value = "/login")
	@ResponseBody
	public Mono<RetData<Map<String, Object>>> sysuserLogin(ServerWebExchange exchange,@RequestBody SysUser paramSysUser) throws Exception {
		
		ServerHttpRequest request =  exchange.getRequest();
		RetData<Map<String, Object>> retData = new RetData<Map<String, Object>>();
		
		String username = paramSysUser.getUsername();
		String password = paramSysUser.getPassword();

		if(username==null || username.equals("")) {
			RetDataHead retHead = new RetDataHead();
			retHead.setCode(GatewayRetCodeEnum.RET_CODE_0802001.getCode());
			retHead.setMessage(GatewayRetCodeEnum.RET_CODE_0802001.getMessage());
			retData.setRetHead(retHead);
			logBPO.enableUserLoginLog(username, retData,request);
			return Mono.just(retData);
		}
		if(password==null || password.equals("")) {
			RetDataHead retHead = new RetDataHead();
			retHead.setCode(GatewayRetCodeEnum.RET_CODE_0802002.getCode());
			retHead.setMessage(GatewayRetCodeEnum.RET_CODE_0802002.getMessage());
			retData.setRetHead(retHead);
			logBPO.enableUserLoginLog(username, retData,request);
			return Mono.just(retData);
		}
		
		try {
			SysUser sysUser = sysUserBPO.doGetSysUserByUsername(username);
			// 用户不存在
			if(sysUser==null || "".equals(sysUser.getId())) {
				RetDataHead retHead = new RetDataHead();
				retHead.setCode(GatewayRetCodeEnum.RET_CODE_0801013.getCode());
				retHead.setMessage(GatewayRetCodeEnum.RET_CODE_0801013.getMessage());
				retData.setRetHead(retHead);
				logBPO.enableUserLoginLog(username, retData,request);
				return Mono.just(retData);
			}
			// 密码不匹配
			if(!sysUser.getPassword().equals(password)) {
				RetDataHead retHead = new RetDataHead();
				retHead.setCode(GatewayRetCodeEnum.RET_CODE_0801014.getCode());
				retHead.setMessage(GatewayRetCodeEnum.RET_CODE_0801014.getMessage());
				retData.setRetHead(retHead);
				logBPO.enableUserLoginLog(username, retData,request);
				return Mono.just(retData);
			}
			// 账号停用
			if(!"1".equals(sysUser.getUserStatus())) {
				RetDataHead retHead = new RetDataHead();
				retHead.setCode(GatewayRetCodeEnum.RET_CODE_0801012.getCode());
				retHead.setMessage(GatewayRetCodeEnum.RET_CODE_0801012.getMessage());
				retData.setRetHead(retHead);
				logBPO.enableUserLoginLog(username, retData,request);
				return Mono.just(retData);
			}
			Map<String, Object> bodySysUser = getLoginResponseBody(sysUser);
			retData.setRetBody(bodySysUser);

		} catch (Exception er) {
			er.printStackTrace();
			RetDataHead retHead = new RetDataHead();
			retHead.setCode(GatewayRetCodeEnum.RET_CODE_0899999.getCode());
			retHead.setMessage(GatewayRetCodeEnum.RET_CODE_0899999.getMessage());
			retData.setRetHead(retHead);
			logBPO.enableUserLoginLog(username, retData,request);
			return Mono.just(retData);
		}
		logBPO.enableUserLoginLog(username, retData,request);
		return Mono.just(retData);
	}
	
	
	@RequestMapping(value = "/getUserByToken")
	public Map<String, Object> getUserByToken(String token) throws Exception {
		SysUser sysUser = (SysUser) redisService.hget(WebSecurityConstants.REDIS_MAP_KEY_TOKEN_USERINFO, token);
		Map<String, Object> bodySysUser = userToMap(sysUser);
		bodySysUser.put("token", token);
		return bodySysUser;
	}
	
	private Map<String, Object> getLoginResponseBody(SysUser sysUser) throws Exception {
		
		// 生成token
		String generateToken = BaseUuidUtil.getUUID();
		// token 生成时间
		String tokenCreateTime = BaseDateUtil.getCurrentTime();
		sysUser.setToken(generateToken);
		sysUser.setTokenCreateTime(tokenCreateTime);
		
		// 是否启用REDIS
		if(WebSecurityConstants.REDIS_ENABLED) {
			sysUserRedisBPO.modifyByRedis(sysUser);
		}
		else {
			// 更新token
			sysUserBPO.modifyById(sysUser);
		}
		Map<String, Object> bodySysUser = userToMap(sysUser);
		bodySysUser.put("token", generateToken);
		return bodySysUser;
	}
	
	private Map<String, Object> userToMap(Object obj) {
		Map<String, Object> bodySysUser = new HashMap<String, Object>();
		if(obj instanceof SysUser) {
			SysUser sysUser = (SysUser) obj;
			bodySysUser.put("username", sysUser.getUsername());
			bodySysUser.put("realName", sysUser.getRealName());
			bodySysUser.put("id", sysUser.getId());
			bodySysUser.put("userId", sysUser.getId());
			bodySysUser.put("organId", sysUser.getOrganId());
			bodySysUser.put("organCode", sysUser.getOrganCode());
			bodySysUser.put("organName", sysUser.getOrganName());
			bodySysUser.put("addOrganIds", sysUser.getAddOrganIds());
			bodySysUser.put("addOrganCodes", sysUser.getAddOrganCodes());
			bodySysUser.put("addOrganNames", sysUser.getAddOrganNames());
			bodySysUser.put("sysRoleIds", sysUser.getSysRoleIds());
			bodySysUser.put("sysRoleNames", sysUser.getSysRoleNames());
			bodySysUser.put("sysDutyIds", sysUser.getSysDutyIds());
			bodySysUser.put("sysDutyNames", sysUser.getSysDutyNames());
			bodySysUser.put("grantOrganIds", sysUser.getGrantOrganIds());
			bodySysUser.put("grantOrganCodes", sysUser.getGrantOrganCodes());
			bodySysUser.put("grantOrganNames", sysUser.getGrantOrganNames());
		}
		if(obj instanceof JSONObject) {
		    JSONObject jsonObject = (JSONObject) obj;
			bodySysUser.put("username", jsonObject.get("username"));
			bodySysUser.put("realName", jsonObject.get("realName"));
			bodySysUser.put("id", jsonObject.get("id"));
			bodySysUser.put("userId", jsonObject.get("userId"));
			bodySysUser.put("organId", jsonObject.get("organId"));
			bodySysUser.put("organCode", jsonObject.get("organCode"));
			bodySysUser.put("organName", jsonObject.get("organName"));
			bodySysUser.put("addOrganIds", jsonObject.get("addOrganIds"));
			bodySysUser.put("addOrganCodes", jsonObject.get("addOrganCodes"));
			bodySysUser.put("addOrganNames", jsonObject.get("addOrganNames"));
			bodySysUser.put("sysRoleIds", jsonObject.get("sysRoleIds"));
			bodySysUser.put("sysRoleNames", jsonObject.get("sysRoleNames"));
			bodySysUser.put("sysDutyIds", jsonObject.get("sysDutyIds"));
			bodySysUser.put("sysDutyNames", jsonObject.get("sysDutyNames"));
			bodySysUser.put("grantOrganIds", jsonObject.get("grantOrganIds"));
			bodySysUser.put("grantOrganCodes", jsonObject.get("grantOrganCodes"));
			bodySysUser.put("grantOrganNames", jsonObject.get("grantOrganNames"));
		}
		else {

		}
		return bodySysUser;
	}
	
}
